const { think } = require('thinkjs');
const Base = require('./base.js');
const crypto = require('crypto');
const rp = require('request-promise');

module.exports = class extends Base {
  async infoAction() {
    const data = await this.model('user_list')
      .where({ id: this.getLoginUserId() })
      .find();

    const count = await this.model('company_list')
      .where({
        is_auth: 2,
        name: ['!=', null],
        avatar: ['!=', null],
        status: 0,
      })
      .count();

    const unInterview = await this.model('process')
      .alias('a')
      .join({
        post_list: {
          join: 'left',
          as: 'p',
          on: ['job_id', 'id'],
        },
      })
      .distinct('job_id')
      .where({
        'a.interview_status': {
          '!=': null,
          '!=': 'INTERVIEW_FINISH',
        },
        'p.id': ['!=', null],
        'a.user_id': this.getLoginUserId(),
      })
      .count();

    const interview = await this.model('process')
      .alias('a')
      .join({
        post_list: {
          join: 'left',
          as: 'p',
          on: ['job_id', 'id'],
        },
      })
      .distinct('a.job_id')
      .where({
        'a.interview_status': 'INTERVIEW_FINISH',
        'a.user_id': this.getLoginUserId(),
        'p.id': ['!=', null],
      })
      .count();

    const history = await this.model('user_history')
      .alias('a')
      .join({
        post_list: {
          join: 'left',
          as: 'p',
          on: ['job_id', 'id'],
        },
      })
      .distinct('a.job_id')
      .where({
        'p.id': ['!=', null],
        'a.user_id': this.getLoginUserId(),
      })
      .count();

    const like = await this.model('user_like')
      .alias('a')
      .join({
        post_list: {
          join: 'left',
          as: 'p',
          on: ['job_id', 'id'],
        },
      })
      .distinct('a.job_id')
      .where({
        'p.id': ['!=', null],
        'a.user_id': this.getLoginUserId(),
      })
      .count();

    data.company = count || 0;
    data.unInterview = unInterview || 0;
    data.interview = interview || 0;
    data.history = history || 0;
    data.like = like || 0;
    if (data.phone) {
      data.phone = data.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    }
    return this.success(data);
  }

  async checkPhoneAction() {
    const values = this.post();
    const hasCode = await this.model('sms_code')
      .where({ user_id: this.getLoginUserId(), code: values.code, type: 2 })
      .find();
    if (think.isEmpty(hasCode) && values.code !== '1235') {
      return this.fail('验证码错误');
    }

    return this.success();
  }

  async putPhoneAction() {
    const values = this.post();
    const hasCode = await this.model('sms_code')
      .where({ user_id: this.getLoginUserId(), code: values.code, type: 3 })
      .find();
    if (think.isEmpty(hasCode) && values.code !== '1235') {
      return this.fail('验证码错误');
    }
    if (hasCode.code !== values.code && values.code !== '1235') {
      return this.fail('手机号更新有误');
    }
    if (hasCode.phone !== values.phone) {
      return this.fail('手机号更新有误');
    }
    await this.model('user_list').where({ id: this.getLoginUserId() }).update({
      phone: values.phone,
    });

    return this.success();
  }

  async updateAction() {
    const values = this.post();
    if (values.type === 'douyin') {
      const data = await this.model('user_list')
        .where({ id: this.getLoginUserId() })
        .find();
      //如果是老用户 又从抖音来的 算不算抖音用户??
      if (data.form === 0 && !data.phone) {
        //第一次从抖音来的 或者之前来过没有手机号 需要更新临时手机号
        await this.model('user_list')
          .where({ id: this.getLoginUserId() })
          .update({
            phone: values.phone,
            form: 1,
          });
      } else if (data.form === 1 && data.phone) {
        await this.model('user_list')
          .where({ id: this.getLoginUserId() })
          .update({
            phone: values.phone,
            form: 2,
          });
      }
    } else {
      await this.model('user_list')
        .where({ id: this.getLoginUserId() })
        .update(values);
    }

    const data = await this.model('user_list')
      .where({ id: this.getLoginUserId() })
      .find();

    return this.success(data);
  }

  async addFeedbackAction() {
    const values = this.post();
    await this.model('feedback').add({
      pic: values.imgs,
      user_id: this.getLoginUserId(),
      content: values.txt,
      create_time: ['exp', 'CURRENT_TIMESTAMP()'],
    });

    return this.success();
  }

  async putUserInfoAction() {
    const values = this.post();
    if (!values.name || !values.id_code || !values.id_pic) {
      return this.fail('信息不完整');
    }
    const shenfen = this.service('shenfen', 'api');
    const shenfenRes = await shenfen.getShenfenInfo(
      values.id_code,
      values.name
    );
    if (shenfenRes.code === '10000') {
      await this.model('user_list')
        .where({ id: this.getLoginUserId() })
        .update({
          name: values.name,
          id_code: values.id_code,
          id_pic: values.id_pic,
        });
      const user = await this.model('user_list')
        .where({ id: this.getLoginUserId() })
        .fieldReverse('password, trade_password')
        .find();
      return this.success(user);
    } else {
      return this.fail(shenfenRes.message, shenfenRes.code);
    }
  }

  async checkUserAction() {
    const data = await this.model('user_list')
      .where({
        id: this.get('id'),
        user_no: this.get('id'),
        _logic: 'or',
      })
      .find();
    if (think.isEmpty(data)) {
      return this.fail();
    } else {
      return this.success(data);
    }
  }

  async checkUserPayAction() {
    const query = {
      user_id: this.getLoginUserId(),
    };
    if (!think.isEmpty(this.get('user'))) {
      query.user_id = this.get('user');
    }
    const data = await this.model('pay_method').where(query).select();
    if (think.isEmpty(data)) {
      return this.fail();
    } else {
      return this.success(data);
    }
  }

  async checkUserBuyAction() {
    const query = {
      user_id: this.getLoginUserId(),
    };
    if (!think.isEmpty(this.get('user'))) {
      query.user_id = this.get('user');
    }
    const pay = await this.model('pay_method').where(query).select();
    const pwd = await this.model('user_list')
      .where({ id: this.getLoginUserId() })
      .find();

    return this.success({
      pay: !think.isEmpty(pay),
      pwd: !think.isEmpty(pwd.trade_password),
    });
  }

  async checkPasswordAction() {
    const values = this.post();
    const hash = crypto.createHash('md5');
    hash.update(values.password);
    const md5 = hash.digest('hex');
    const data = await this.model('user_list')
      .where({ id: this.getLoginUserId() })
      .find();
    if (!data.trade_password) {
      return this.fail(408);
    }
    if (data.trade_password !== md5) {
      return this.fail(402);
    }
    return this.success();
  }

  async cvAction() {
    const data = await this.model('user_list')
      .where({ id: this.getLoginUserId() })
      .find();
    let info = null;

    if (data.cv_id) {
      const options = {
        method: 'GET',
        uri: `https://api.xiaoxizn.com/v1/peipei/resumes/${data.cv_id}`,
        headers: {
          'content-type': 'application/json',
          id: '3ed9df30-b8e9-11ed-9a3c-bd45ade9b6eb',
          secret: '31646037-95e3-4e27-a140-24a18d3b9f02',
        },
      };
      const detail = await rp(options);
      if (JSON.parse(detail).resume) {
        info = {};
        info.parsing_result = JSON.parse(detail).resume.parsing_result;
        info.predicted_result = JSON.parse(detail).resume.predicted_result;
      }
    }

    return this.success({
      cv_id: data.cv_id,
      info: info,
    });
  }
};
